<script setup name="ConductivityTools">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElFormItem } from 'element-plus'

const props = defineProps({
	isLoading: Boolean,
	selectedElements: Array,
})

const emit = defineEmits(['on-submit'])

const formRef = ref(null)

// 常量定义
const MAX_ELEMENTS = 7 // 最多6个组分
const MAX_SUM_PERCENT = 30 // 总和上限30%
const MIN_ELEMENT_PERCENT = 0.01 // 单个元素最小值0.01%
const MIN_MG_PERCENT = 70 // Mg最低含量70%

// 表单数据
const form = ref({
	composition: {},
	calculation_type: 'both',
	temperature: 373,
})

// 计算其他元素总和（小数形式）
const otherElementsTotal = computed(() => {
	return Object.values(form.value.composition).reduce(
		(sum, val) => sum + (Number(val) || 0),
		0
	)
})

// 计算每个元素的最大允许值（动态约束）
const elementMaxValues = computed(() => {
	const maxValues = {}
	const currentTotal = otherElementsTotal.value

	// 计算每个元素的最大值
	for (const element in form.value.composition) {
		const currentValue = form.value.composition[element] || 0
		// 最大允许值 = 剩余额度 + 当前值 (确保不直接归零)
		const maxAllowed = Math.min(30, 30 - (currentTotal - currentValue))
		maxValues[element] = maxAllowed
	}

	return maxValues
})

// 更新Mg含量（动态计算）
const MgContent = computed(() => {
	return Math.max(MIN_MG_PERCENT, 100 - otherElementsTotal.value).toFixed(2)
})

// 元素输入变化处理（含自动修正）
const updateComposition = (field, newValue) => {
	// 边界控制（0.0001~0.3对应0.01%~30%）
	let correctedValue = Math.min(30, Math.max(0.0001, newValue))

	// 计算其他元素总和（不包括当前字段）
	const otherSum =
		otherElementsTotal.value - (form.value.composition[field] || 0)

	// 自动修正：确保总和不超过30%
	if (otherSum + correctedValue > 30) {
		correctedValue = 30 - otherSum
		ElMessage.warning(`已自动调整为最大可用值 ${correctedValue.toFixed(2)}%`)
	}

	form.value.composition[field] = correctedValue
}

// 校验规则
const validationRules = computed(() => ({
	temperature: [
		{ required: true, message: '请输入温度', trigger: 'blur' },
		{
			pattern: /^\d+(\.\d{1,4})?$/,
			message: '温度必须为数字且最多四位小数',
			trigger: 'blur',
		},
	],
	MgContent: [
		{
			validator: (rule, value, callback) => {
				if (parseFloat(value) < MIN_MG_PERCENT) {
					callback(new Error(`Mg含量必须 ≥ ${MIN_MG_PERCENT}%`))
				} else {
					callback()
				}
			},
			trigger: ['blur', 'change'],
		},
	],
	// 动态生成元素校验规则
	...props.selectedElements.slice(1, MAX_ELEMENTS).reduce((rules, element) => {
		rules[`composition[${element}]`] = [
			{
				required: true,
				message: `${element}含量不能为空`,
				trigger: 'blur',
			},
			{
				validator: (rule, value, callback) => {
					const percent = Number(value)
					if (percent < MIN_ELEMENT_PERCENT) {
						callback(new Error(`不能低于${MIN_ELEMENT_PERCENT}%`))
					} else if (percent > MAX_SUM_PERCENT) {
						callback(new Error(`不能超过${MAX_SUM_PERCENT}%`))
					} else {
						callback()
					}
				},
				trigger: ['blur', 'change'],
			},
		]
		return rules
	}, {}),
}))

const elements = computed(() => {
	return props.selectedElements.map((item) => ({
		label: item,
		props: `composition[${item}]`,
	}))
})

// 提交计算
const submitForm = async () => {
	try {
		await formRef.value.validate()
		emit('on-submit', form.value)
	} catch (error) {
		ElMessage.error('请检查输入数据')
	}
}
</script>

<template>
	<div class="component-form">
		<el-form
			ref="formRef"
			:model="form"
			:rules="validationRules"
			label-width="100px"
		>
			<!-- Mg含量显示 -->
			<el-form-item label="Mg含量" prop="MgContent">
				<el-input
					:value="`${MgContent}%`"
					:class="{
						'error-input': otherElementsTotal > MAX_SUM_PERCENT,
					}"
					readonly
				/>
			</el-form-item>

			<!-- 动态元素输入（最多6个） -->
			<el-form-item
				v-for="(item, index) in elements.slice(1, MAX_ELEMENTS)"
				:key="index"
				:prop="item.props"
				:label="`${item.label}含量(%)`"
			>
				<el-input-number
					v-model="form.composition[item.label]"
					@change="(val) => updateComposition(item.label, val)"
					:min="0.01"
					:precision="2"
					:max="30"
					:controls="false"
					placeholder="0.01% - 30%"
					class="inputNumber"
				/>
			</el-form-item>

			<!-- 温度输入 -->
			<el-form-item label="温度(K)" prop="temperature">
				<div class="tempStyle">
					<el-input-number
						v-model="form.temperature"
						:precision="2"
						:min="298.15"
						:max="2000"
						:controls="false"
						placeholder="请输入温度"
						class="inputNumber"
					/>
					<span class="text">温度(K)：289.15K ～ 2000K</span>
				</div>
			</el-form-item>
		</el-form>

		<!-- 提交按钮 -->
		<div class="form-actions">
			<el-button
				type="primary"
				:disabled="otherElementsTotal > MAX_SUM_PERCENT"
				@click="submitForm"
			>
				开始计算
			</el-button>
		</div>
	</div>
</template>

<style scoped lang="scss">
.sum-indicator {
	display: flex;
	justify-content: space-between;
	padding: 10px 15px;
	margin-bottom: 20px;
	background-color: var(--el-color-primary-light-9);
	border-radius: 4px;
	font-weight: bold;

	&.error {
		background-color: var(--el-color-danger-light-9);
		color: var(--el-color-danger);
	}
}

/* 错误状态样式 */
.error-input {
	:deep(.el-input__inner) {
		color: var(--el-color-danger);
		font-weight: bold;
	}
}

.form-actions {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 10px;
	margin-top: 20px;

	:deep(.el-button) {
		flex: 1;
	}
}

// 表单验证错误状态
:deep(.el-form-item) {
	margin-bottom: 20px !important;
	.el-form-item__error {
		display: block !important;
	}
}

:deep(.inputNumber) {
	width: 100% !important;
	.el-input__wrapper {
		padding: 1px 11px !important;
		.el-input__inner {
			text-align: left;
		}
	}
}

.tempStyle {
	position: relative;
	width: 100%;
	.text {
		position: absolute;
		font-size: 0.75rem;
		bottom: -26.7px;
		right: 0;
	}
}
</style>

<style>
@import url('@/styles/element-plus/form.scss');
</style>
